/*
 * @Author: dadadaXU 1413107032@qq.com
 * @Date: 2025-01-14 21:23:26
 * @LastEditors: dadadaXU 1413107032@qq.com
 * @LastEditTime: 2025-01-14 22:11:15
 * @FilePath: \leetcode\2.两数相加.cpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/*
 * @lc app=leetcode.cn id=2 lang=cpp
 *
 * [2] 两数相加
 */

struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */

class Solution
{
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
    {
        ListNode *l3 = new ListNode();
        ListNode *p = l3;
        int carry = 0; // 进位数据

        while (true)
        {
            if (l1 != nullptr)
            {
                p->val += l1->val;
                l1 = l1->next;
            }
            if (l2 != nullptr)
            {
                p->val += l2->val;
                l2 = l2->next;
            }

            carry = p->val / 10;
            p->val %= 10;

            if (l1 != nullptr || l2 != nullptr || carry != 0)
            {
                p->next = new ListNode(carry);
                p = p->next;
            }
            else
                return l3;
        }

        return l3;
    }
};
// @lc code=end
